<template>
  <div class="app-container flex dirc">
    <!-- 基础信息 -->
    <el-card shadow="hover" v-loading="loading">
      <template #header>
        <span>报销信息</span>
      </template>
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="报销类型:">
          {{ `${Reimburse_Type_Label[typeUpperCase]}费用` }}
        </el-form-item>
        <el-form-item :label="btnTitle" prop="name">
          {{ formData?.title || "请选择" }}
          <el-button v-if="!id" type="primary" class="ml15" @click="showChooseWindow">
            选择{{ btnTitle }}
          </el-button>
        </el-form-item>
        <el-form-item label="申请理由:">
          <el-input type="textarea" v-model="applyMark" autocomplete="off" />
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="flex1 mt10 full" shadow="hover" v-if="formData" v-loading="loading">
      <template #header>
        <span>报销清单</span>
      </template>
      <el-table ref="dataTableRef" :data="contractItems" height="calc(100% - 40px)" highlight-current-row
        default-expand-all :preserve-expanded-content="typeUpperCase === 'NORM'" v-if="formData">
        <el-table-column type="expand" v-if="typeUpperCase === 'NORM'">
          <template #default="scope">
            <div class="disf alc pl60 pb10">
              <b>关联的工艺人员：</b>
              <el-select v-model="scope.row.taskGyDispatchIds" class="flex1" placeholder="请选择" multiple>
                <el-option v-for="item in dispatchMap[scope.row.materialId]" :key="item.id"
                  :label="`${item.taskName}-${item.name}-${item.username}`" :value="item.id!"></el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="材料名称" prop="name" />
        <el-table-column label="材料类型" width="120">
          <template #default="scope">
            {{ SaleMealTypeLabel[scope.row.materialType] }}
          </template>
        </el-table-column>
        <el-table-column label="规格" prop="spec" />
        <el-table-column label="单位" prop="unit" />
        <template v-if="typeUpperCase === 'NORM' || typeUpperCase === 'INSTRUMENT'">
          <el-table-column label="已申报数量" prop="reimburseTotalQuantity" />
          <el-table-column label="已申报金额" prop="reimburseTotalAmount" />
          <el-table-column label="数量" align="center" prop="quantity" width="120">
            <template #default="scope">
              <el-input-number v-model="scope.row.quantity" style="width: 100%" size="small" :min="0"
                :max="scope.row.max" />
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="amount" width="160">
            <template #default="scope">
              <el-input-number v-model="scope.row.amount" style="width: 100%" size="small" :min="0" :precision="2" />
            </template>
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column label="数量" align="center" prop="quantity" />
          <el-table-column label="单价" prop="amount" />
        </template>
        <el-table-column label="操作" fixed="right" width="100" align="center">
          <template #default="scope">
            <el-button size="small" v-if="typeUpperCase === 'NORM' || typeUpperCase === 'INSTRUMENT'" type="danger" link
              @click="handleDeleteItem(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt10 disf alc juc">
        <el-button class="ml10" type="primary" v-if="typeUpperCase === 'NORM' || typeUpperCase === 'INSTRUMENT'" plain
          @click="showMaterialWindow()">
          添加选项
        </el-button>
        <el-button class="ml10" @click="handleSave">保存</el-button>
        <el-button class="ml10" type="primary" @click="handleSubmit">提交报销</el-button>
      </div>
    </el-card>
    <!-- 项目弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1100px" @close="closeChooseWindow">
      <!-- :ex-query="{ statuses: ContractBuildStatus.ACTIVITY }" -->
      <PurchaseSelector ref="purchaseRef" :type="typeUpperCase"
        v-if="typeUpperCase === 'MAIN' || typeUpperCase === 'SUB'" />
      <BuildSelector ref="contractRef" v-if="typeUpperCase === 'NORM' || typeUpperCase === 'INSTRUMENT'" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="chooseDone">确 定</el-button>
          <el-button @click="closeChooseWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 弹窗：选材料-->
    <el-dialog v-model="chooseMaterialVisible" title="选择材料" width="800px" @close="closeMaterialWindow">
      <MaterialSelector v-if="chooseMaterialVisible" :type="typeUpperCase" ref="materialRef" :exQuery="exQuery"
        :withNorm="true" operation="add" @addItem="addMaterial" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="chooseMaterialDone">确 定</el-button>
          <el-button @click="closeMaterialWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { SaleMealTypeLabel } from "@/api/business/material/sealMeal.api";
import PurchaseSelector from "@/views/fee/purchase/PurchaseSelector.vue";
import BuildSelector from "@/views/flow/buildPlan/BuildSelector.vue";
import router from "@/router";
import { useTagsViewStore } from "@/store";
import ReimburseAPI, { Reimburse_Type_Label, ReimburseItemVO, ReimbursePageVO } from "@/api/fee/reimburse.api";
import PurchaseAPI from "@/api/fee/purchase.api";
import ContractLedgerAPI from "@/api/flow/contractLedger.api";
import TaskGyDispatchAPI, { TaskGyDispatchItem } from "@/api/flow/taskGyDispatch.api";
import { toMapList } from "@/utils";
import { MaterialPageVO } from "@/api/business/material/material.api";
import MaterialSelector from "@/views/business/material/material/MaterialSelector.vue";
defineOptions({
  name: "ReimburseEdit",
  inheritAttrs: false,
});

const route = useRoute();

const id = ref(""); //申请id
const type = ref(""); //材料类型
const typeUpperCase = computed(() => type.value.toUpperCase()); // 材料类型大写
const tagsViewStore = useTagsViewStore();
const isOthers = computed(
  () => typeUpperCase.value === "NORM" || typeUpperCase.value === "INSTRUMENT"
); // 非采购单（定额、器具）
const btnTitle = computed(() => (isOthers.value ? "项目" : "申购单"));
const loading = ref(false);
const formData = ref<{ id: string; contractId: string; title: string }>(); //申购单信息
const applyMark = ref(""); //表单-申请原因
const contractItems = ref<ReimburseItemVO[]>([]); //报销列表
const dispatchMap = ref<{ [key: string]: TaskGyDispatchItem[] }>({}); //工艺人员-按定额分
const dialog = reactive({
  title: "请选择申购单",
  visible: false,
});

const formRef = ref();
const purchaseRef = ref();
const contractRef = ref();

const materialRef = ref();
const chooseMaterialVisible = ref(false);
const exQuery = ref({
})

onActivated(() => {

  // if (route.query.id == id.value && route.query.type == type.value) return;
  // id变动 重置数据
  id.value = route.query.id as string;
  type.value = (route.query.type as string) || "main";
  applyMark.value = "";
  formData.value = undefined;
  id.value && loadDetail();
  setExQuery();
});

function showChooseWindow() {
  dialog.visible = true;
  // console.log("type", type.value, typeUpperCase.value === "INSTRUMENT");
  if (isOthers.value) {
    nextTick(() => {
      contractRef.value.handleQuery();
    });
  } else {
    nextTick(() => {
      purchaseRef.value.handleQuery();
    });
  }
}

async function loadDetail() {
  if (!id.value || id.value === "0") {
    return;
  }
  loading.value = true;
  try {
    const data = await ReimburseAPI.load(id.value);
    formData.value = { ...data };
    applyMark.value = data.lastRecord?.applyMark || "";
    contractItems.value = data.items.map((item) => ({
      ...item,
      amount: parseFloat(item.amount as string),
      max: Math.max(item.contractQuantity! - item.totalQuantity!, 0),
      reimburseTotalQuantity: `${item.totalQuantity} / ${item.contractQuantity}`,
      reimburseTotalAmount: `${item.totalAmount} / ${(parseFloat(item.contractPrice!) * item.contractQuantity!).toFixed(2)}`,
      taskGyDispatchIds: item.reimburseItemTasks?.map((t) => t.taskGyDispatchId),
    }));
    // 人工需加载备选
    if (typeUpperCase.value === "NORM") {
      loadGyTask(data.contractId);
    }
  } catch (error) {
    console.error(error);
  }
  loading.value = false;
}

/** 加载合同的工艺人员 */
async function loadGyTask(id: string) {
  const items = await TaskGyDispatchAPI.loadByContractId(id);
  dispatchMap.value = toMapList(items, "normId");
}

function closeChooseWindow() {
  dialog.visible = false;
}

// 确认项目
async function chooseDone() {
  closeChooseWindow();
  if (isOthers.value) {
    chooseBuildContractDone();
  } else {
    choosePurchaseDone();
  }
}

/** 完成申购选择 */
async function choosePurchaseDone() {
  let choosed = purchaseRef.value.getChecked();
  if (!choosed) return;
  formData.value = choosed;
  // 加载报销列表
  try {
    const data = await PurchaseAPI.load(choosed.id);
    contractItems.value = data.items.map((d) => ({
      ...d,
      amount: parseFloat(d.amount as string),
      reimburseTotalQuantity: `${d.totalQuantity} / ${d.contractQuantity}`,
      reimburseTotalAmount: `${d.totalAmount} / ${(parseFloat(d.contractPrice!) * d.contractQuantity!).toFixed(2)}`,
    }));
  } catch (error) {
    console.error("加载报销列表失败");
  }
}

/** 完成项目选择 */
async function chooseBuildContractDone() {
  let choosed = contractRef.value.getChecked();
  if (!choosed) return;
  formData.value = choosed;
  if (formData.value) {
    formData.value.title = choosed.contractName;
  }
  const isRenGong = typeUpperCase.value === "NORM";
  if (isRenGong) {
    loadGyTask(choosed.contractId);
  }
  // 加载报销列表
  try {
    const data = await ContractLedgerAPI.loadLastByContractId(
      choosed.contractId,
      false,
      true,
      isRenGong
    );
    contractItems.value = data
      .filter((cItem) => typeUpperCase.value.includes(cItem.itemType))
      .map((c) => ({
        ...c,
        amount: parseFloat(c.price as string) || 0,
        materialId: c.resourceId,
        materialType: c.itemType,
        max: Math.max(c.quantity - c.reimburseTotalQuantity!, 0),
        reimburseTotalQuantity: `${c.reimburseTotalQuantity} / ${c.quantity}`,
        reimburseTotalAmount: `${c.reimburseTotalAmount} / ${(parseFloat(c.price as string) * c.quantity).toFixed(2)}`,
      }));
  } catch (error) {
    console.error("加载人工列表失败");
  }
}

// 保存按钮
async function handleSave() {
  const result = await save();
  result && ElMessage.success("保存成功");
}

// 提交按钮
async function handleSubmit() {
  if (!applyMark.value) {
    ElMessage.warning("请填写申请理由");
    return;
  }
  const result = await save();
  if (!result) return;
  await submitApply(result);
  ElMessage.success("提交成功");
  await tagsViewStore.closeCurrentView();
  router.push({ path: "/fee/reimburse/" + type.value });
}

// 保存
async function save() {
  loading.value = true;
  // 处理数据
  const filterData = contractItems.value.filter((item) => item.quantity > 0);
  if (filterData.length === 0) {
    ElMessage.warning("报销项中必须有数量大于0的");
    loading.value = false;
    return;
  }
  try {
    const sendData = {
      id: id.value || "",
      purchaseId: (!isOthers.value && formData.value?.id) || "",
      contractId: formData.value?.contractId || "",
      title: `${formData.value?.title}-${SaleMealTypeLabel[typeUpperCase.value]}-报销申请`,
      items: filterData,
      type: typeUpperCase.value,
      amount: sumTotal(),
      applyMark: applyMark.value,
    };
    const res = sendData.id
      ? await ReimburseAPI.update(sendData)
      : await ReimburseAPI.create(sendData);
    loading.value = false;
    return res;
  } catch (error) {
    console.error("保存失败");
  }
  loading.value = false;
}

// 申请提交
async function submitApply(res: ReimbursePageVO) {
  loading.value = true;
  try {
    await ReimburseAPI.apply({
      id: res.id,
    });
  } catch (error) {
    console.error("提交失败");
  }
  loading.value = false;
}

// 计算总额
function sumTotal() {
  const total = contractItems.value.reduce((sum, item) => {
    return sum + (item.amount as number) * item.quantity;
  }, 0);
  return total.toFixed(2);
}

function setExQuery() {
  var type = (route.query.type as string) || "main";
  if (type.toLocaleUpperCase() == 'NORM') {
    exQuery.value = { "renGong": true }
  } else {
    exQuery.value = { "renGong": false }
  }
}

/**以下选择材料 */
function showMaterialWindow() {
  chooseMaterialVisible.value = true;
  console.log("type:", typeUpperCase)
  setExQuery();
  nextTick(() => {
    materialRef.value.handleQuery();
  });
}

function chooseMaterialDone() {
  chooseMaterialVisible.value = false;
}

function closeMaterialWindow() {
  chooseMaterialVisible.value = false;
}

/**
 * 添加材料
 */
async function addMaterial(item: MaterialPageVO) {
  const oMeal = contractItems.value.find((m) => m.materialId === item.id);

  if (oMeal) {
    oMeal.quantity++;
  } else {
    contractItems.value.push({
      materialId: item.id || '0',
      quantity: 1,
      name: item.name || "",
      amount: item.price || 0,
      unit: item.unit || "",
      materialType: item.type || "",
      remark: "",
      spec: item.spec || "",
    });
  }
}

// 删除材料
function handleDeleteItem(item: ReimburseItemVO) {
  contractItems.value = contractItems.value.filter((i) => i.id !== item.id);
}
</script>

<style lang="scss" scoped></style>
